package net.bcxuexi.socket.model;

import java.io.IOException;
import java.net.Socket;

import net.bcxuexi.config.Config;
import net.bcxuexi.socket.stream.ReadStream;
import net.bcxuexi.socket.stream.WriteStream;
import net.bcxuexi.tools.MyLog;
import net.bcxuexi.tools.StringUtils;

public class SocketModel {
	/**socket编号*/
	private String connId;
	/**域名*/
	private String socketDomain;
	/**
	 * socket类型
	 * control:控制信息socket
	 * data:数据传输
	 * inner:连接内网服务器端口的socket
	 */
	private String type;
	
	private Socket socket;
	
	/**
	 * 如果type是inner类型，需要设置innerIp、innerPort、proxyConnId
	 */
	private String innerIp;
	private int innerPort;
	/**
	 * 如果type是inner类型，需要proxyConnId
	 * 外部请求外网服务器端口的socket连接的connId
	 */
	private String proxyConnId;
	
	/**socket信息读取对象*/
	private ReadStream readStream;
	/**socket信息写对象*/
	private WriteStream writeStream;
	public String getConnId() {
		return connId;
	}
	public void setConnId(String connId) {
		this.connId = connId;
	}
	
	public String getSocketDomain() {
		return socketDomain;
	}
	public void setSocketDomain(String socketDomain) {
		this.socketDomain = socketDomain;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	
	
	public Socket getSocket() {
		return socket;
	}
	public void setSocket(Socket socket) {
		this.socket = socket;
	}
	
	public ReadStream getReadStream() {
		return readStream;
	}
	public void setReadStream(ReadStream readStream) {
		this.readStream = readStream;
	}
	public WriteStream getWriteStream() {
		return writeStream;
	}
	public void setWriteStream(WriteStream writeStream) {
		this.writeStream = writeStream;
	}
	
	public String getInnerIp() {
		return innerIp;
	}
	public void setInnerIp(String innerIp) {
		this.innerIp = innerIp;
	}
	public int getInnerPort() {
		return innerPort;
	}
	public void setInnerPort(int innerPort) {
		this.innerPort = innerPort;
	}
	public String getProxyConnId() {
		return proxyConnId;
	}
	public void setProxyConnId(String proxyConnId) {
		this.proxyConnId = proxyConnId;
	}
	@Override
	public String toString() {
		String msg = "socket类型："+type+",connId="+connId;
		if(!StringUtils.isBlack(innerIp)){
			msg += ",innerIp="+innerIp+",innerPort="+innerPort;
		}
		return msg;
	}
	public boolean isActive(){
		if(socket==null||socket.isClosed()){
			return false;
		}
		if(socket.isInputShutdown()||socket.isOutputShutdown()){
			return false;
		}
		return true;
	}
	public void closeSocket(String msg){
		MyLog.info(msg);
		try {
			if(socket!=null&&!socket.isClosed()){
				socket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(readStream!=null){
				readStream.stopRead();
			}
			if(writeStream!=null){
				writeStream.stopWrite();
			}
			
			readStream=null;
			writeStream=null;
			socket=null;
			
		}
	}
}
